package com.baidu.lib_common.utils

import android.content.Context
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkRequest
import com.baidu.lib_common.constant.NetWorkAvailableEvent
import com.baidu.lib_common.constant.NetWorkLostEvent
import com.baidu.lib_leancloud.LeanCloudManager
import org.greenrobot.eventbus.EventBus

class NetWorkUtils private constructor(){
    private var networkCallback: ConnectivityManager.NetworkCallback ?= null
    var context: Context ?= null
    companion object{
        val instance = NetWorkUtils()
    }
    fun initNetWorkUtils(context: Context){
        this.context = context
    }
    fun registerNetWorkCallback(available:()->Unit,lost:()->Unit){
        val cm:ConnectivityManager = context!!.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val netWork: Network?= cm.activeNetwork
        if(netWork == null){
            EventBus.getDefault().postSticky(NetWorkLostEvent())
        }else{
            EventBus.getDefault().postSticky(NetWorkAvailableEvent())
        }
        networkCallback = object : ConnectivityManager.NetworkCallback(){
            override fun onAvailable(network: Network) {
                super.onAvailable(network)
                available()
            }

            override fun onLost(network: Network) {
                super.onLost(network)
                lost()
            }
        }.also {
            cm.registerNetworkCallback(
                NetworkRequest.Builder()
                    .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
                    .build(),
                it
            )
        }

    }
    fun unRegisterNetWorkCallback(){
        val cm:ConnectivityManager = context!!.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        cm.unregisterNetworkCallback(networkCallback!!)
    }
}